$(document).ready(function () {

    init();
    initTable();
    allClazz();
    $("#b_cencle").click(function() {
        $("#div_update").css('display','none');
    })
    function initCheck(eventIds) {
        $.ajax({
            type:"get",
            url:"/event/allEvent",
            dataType:"json",
            success:function(data) {
                for (var i in data) {
                    $("#events").append("<li><input type='checkbox' class='events' value='" + data[i].id + "' name='events'/>" + data[i].name + "</li>");
                }
                var events = $(".events");
                for(var i=0;i<events.length;i++){
                    for(var j=0;j<eventIds.length;j++){
                        if(events[i].value == eventIds[j]){
                            events[i].checked = true;
                            break;
                        }
                    }
                }
            }
        })
    }

    function initTable() {
    $.ajax({
        type:"get",
        url:"/UserEvents/getAllUserEvents",
        dataType:"json",
        async:false,
        success:function(data) {
            if(data!=null&&data!=""){
                for(var i in data){
                    var userName="";
                    var eventNames="";
                    var user={
                        id:data[i].userId
                    }
                    $.ajax({
                        type:"get",
                        url:urlToUser+"/user/getUserById",
                        data:user,
                        async:false,
                        dataType:"json",
                        success:function(result) {
                            userName=result.name;
                        }
                    })
                    var eventIds=(data[i].eventId).split(",");
                    for(var j in eventIds) {
                        var event={
                            id:eventIds[j]
                        }
                        $.ajax({
                            type: "post",
                            url:"/event/getEventById",
                            data:event,
                            dataType:"json",
                            async:false,
                            success:function(res) {
                                eventNames+=res.name;
                                eventNames+=" ";
                            }
                        })
                    }
                    $("#t1").append("<tr><td>"+data[i].id+"</td><td>"+userName+"</td><td>"+eventNames+"</td><td><input type='button' class='b_update' value='修改'></td><td><input type='button' class='b_delete' value='删除'></td></tr>")


                }


            }
            $(".b_update").click(function() {
                $("#div_update").css('display','block');
                var id = $(this).parent().parent().find("td").eq(0).text();
                var name = $(this).parent().parent().find("td").eq(1).text();
                $("#text_id").val(id);
                $("#text_name").val(name);
                var userEvents={
                    id:id
                }
                $.ajax({
                    type:"get",
                    url:"/UserEvents/getUserEventsById",
                    data:userEvents,
                    dataType:"json",
                    success:function(data) {
                        var eventIds=((data.eventId).split(","));
                        $("input[name='events']:checkbox").each(function(){
                            $(this).parent('li').remove();
                        });
                        initCheck(eventIds);
                    }
                })
            })
            $(".b_delete").click(function() {
                var id = $(this).parent().parent().find("td").eq(0).text();
                var userevents={
                    id:id
                }
                if(confirm("确认是否删除？")){
                    $.ajax({
                        type:"post",
                        url:"/UserEvents/deleteUsereventsById",
                        data:userevents,
                        dataType:"text",
                        success:function(data) {
                            if(data==1){
                                alert("删除成功！");
                                initTable();
                            }
                        }
                    })
                }
            })
        }
    })
}

    function allClazz() {
        $.ajax({
            type: "GET",
            url: urlToUser+"/clazz/allClazz",
            dataType: "json",
            async:false,
            success: function (data) {
                if (data != null || data != "") {
                    var sClazz = $("#selectClazz");
                    for (var i in data) {
                        if(i==0){
                            sClazz.append("<option selected='selected' value=" + data[i].id + ">" + data[i].name + "</option>");
                            allStudent(data[i].id);
                        }
                        else {
                            sClazz.append("<option value=" + data[i].id + ">" + data[i].name + "</option>");
                        }
                    }
                }
            }
        })

    }

    $('#selectClazz').change(function(){
        $("#selectStudent").empty();
        allStudent($("#selectClazz").val());
    });


    function allStudent(clazzId) {
        var clazzID = clazzId;
        var clazz={
            id:clazzID
        }
        $.ajax({
            type: "POST",
            url: urlToUser+"/user/getUserByClazzId",
            data:clazz,
            dataType: "json",
            async:false,
            success: function (data) {
                if (data != null || data != "") {
                    var sClazz = $("#selectStudent");
                    for (var i in data) {
                        if(data[i].type=="student") {
                            if (i == 0) {
                                sClazz.append("<option selected='selected' value=" + data[i].id + ">" + data[i].name + "</option>");
                            }
                            else {
                                sClazz.append("<option value=" + data[i].id + ">" + data[i].name + "</option>");
                            }
                        }

                    }
                }
            }
        })
    }


    $("#b_add").click(function () {
        var userID = $("#selectStudent  option:selected").val();
        var eventID="";
        $('input[name="header"]:checked').each(function(i){
            if(0==i){
                eventID = $(this).val();
            }else{
                eventID+= (","+$(this).val());
            }
        });
        var UserEvents={
            userId:userID,
            eventId:eventID
        }
        $.ajax({
            type:"post",
            url:"/UserEvents/addUserEvents",
            data:UserEvents,
            dataType:"text",
            success:(function (data) {
                if(1==data){
                    alert("添加成功！！！")
                }else {
                    alert("添加失败！！！")
                }
            })
        })

    })

    function init() {
        $("#t1 tr:not(:first)").empty();
        //clearTable(t1);
        $.ajax({
            type: "GET",
            url: "/event/allEvent",
            dateType: "json",
            success: function (data) {
                if (data != null || data != "") {
                    var event=$("#event");
                    for (var i in data) {
                        event.append("<li><input type='checkbox' value='"+data[i].id+"' name='header'/>"+data[i].name+ "\t("+data[i].startTime+"--"+data[i].endTime+")"+"</li>");
                    }
                }
            }

        })
    }
        $("#b_update").click(function() {
            var id=$("#text_id").val();
            var events="";
            $('input[name="events"]:checked').each(function(i){
                if(0==i){
                    events = $(this).val();
                }else{
                    events+= (","+$(this).val());
                }
            });
            var userevents={
                id:id,
                eventId:events
            }
            $.ajax({
                type:"post",
                url:"/UserEvents/updateUserEventsById",
                data:userevents,
                dataType:"text",
                success:function(data) {
                    if(data==1){
                        alert("更新成功！");
                        initTable();
                    }
                }
            })
        })



})